use leptos::prelude::*;
use serde_json::{Map, Value};
struct ContextMenu {
    key: String,
    name: String,
    row_data: RwSignal<Map<String, Value>>,
}
pub struct ContextMenus {
    menus: Vec<ContextMenu>,
}
impl ContextMenus {
    pub fn new() -> Self {
        Self { menus: Vec::new() }
    }
    pub fn add_menu(&mut self, key: String, name: String) {
        self.menus.push(ContextMenu {
            key,
            name,
            row_data: RwSignal::new(Map::new()),
        });
    }
    pub fn get_menu_name(&self, key: &str) -> String {
        self.menus
            .iter()
            .find(|m| m.key == key)
            .map(|m| m.name.clone())
            .expect(&format!("上下文中不存在指定action: {}", key))
    }
    pub fn set_row_data(&self, key: &str, data: Map<String, Value>) {
        if let Some(menu) = self.menus.iter().find(|m| m.key == key) {
            menu.row_data.set(data);
        }
    }
    pub fn del_row_data(&self, key: &str) {
        if let Some(menu) = self.menus.iter().find(|m| m.key == key) {
            menu.row_data.set(Map::new());
        }
    }
    pub fn get_row_data(&self, key: &str) -> RwSignal<Map<String, Value>> {
        self.menus
            .iter()
            .find(|m| m.key == key)
            .map(|m| m.row_data)
            .expect(&format!("上下文中不存在指定action: {}", key))
    }
}

pub fn init_context_menu() -> ContextMenus {
    let mut context_menus = ContextMenus::new();
    context_menus.add_menu("edit".to_string(), "编辑".to_string());
    context_menus.add_menu("delete".to_string(), "删除".to_string());
    context_menus
}
